<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <upload-excel :on-success="handleSuccess" />
      </el-card>
    </div>
  </div>
</template>

<script>
import { importEmployee } from '@/api/employees'
import { formatExcelDate } from '@/utils/index.js'
export default {
  name: 'Import',
  methods: {

    transExcel(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      const res = results.map(zhObj => {
        const enObj = {}
        const zhKeys = Object.keys(zhObj) // ['姓名', '手机号']

        zhKeys.forEach(zhKey => {
          const enKey = mapInfo[zhKey]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            enObj[enKey] = new Date(formatExcelDate(zhObj[zhKey]))
          } else {
            enObj[enKey] = zhObj[zhKey]
          }
        })

        return enObj
      })
      return res
    },
    async handleSuccess({ header, results }) {
      try {
        console.log(header, results)
        const data = this.transExcel(results)
        console.log(data)
        await importEmployee(data)
        this.$message.success('批量导入成功')
        // 3. 回跳到之前的页面
        this.$router.back()
      } catch (err) {
        this.$message.error(err.message)
      }
    }
  }
}

</script>
